package com.company.project.service.impl;

import com.company.project.dao.NavigationMapper;
import com.company.project.model.Navigation;
import com.company.project.service.NavigationService;
import com.company.project.core.AbstractService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;


/**
 * Created by CodeGenerator on 2018/10/08.
 */
@Service
@Transactional
public class NavigationServiceImpl extends AbstractService<Navigation> implements NavigationService {
    @Resource
    private NavigationMapper navigationMapper;

    @Override
    public List<Navigation> getNavigation() {
        List<Navigation> list = navigationMapper.selectNavigation();
        List<Navigation> resultNavigation = new ArrayList<>();
        Map<Integer,Navigation> map = new HashMap();
        //存放所有一级菜单
        for(Navigation navigation : list){
            if(navigation.getParent()==-1){
                map.put(navigation.getId(),navigation);
            }
        }
        //存放所有二级菜单
        for(Navigation navigation : list){
            if(navigation.getParent()!=-1){
                map.get(navigation.getParent()).getSubNav().add(navigation);
            }
        }
        for (Map.Entry<Integer, Navigation> entry : map.entrySet()){
            Collections.sort(entry.getValue().getSubNav());
            resultNavigation.add(entry.getValue());
        }
        for (Navigation  n : resultNavigation){
            if(n.getSubNav().size()==0){
                n.setSubNav(null);
            }else {
                for (Navigation s : n.getSubNav()){
                    s.setSubNav(null);
                }
            }
        }
        Collections.sort(resultNavigation);
        return resultNavigation;
    }
}
